package cn.com.dcsgo.library.client.service.impl;

import cn.com.dcsgo.library.client.domain.po.Book;
import cn.com.dcsgo.library.client.domain.po.BookCopies;
import cn.com.dcsgo.library.client.domain.po.BorrowRecord;
import cn.com.dcsgo.library.client.domain.vo.BorrowRecordVO;
import cn.com.dcsgo.library.client.enums.BookStatus;
import cn.com.dcsgo.library.client.mapper.BorrowRecordsMapper;
import cn.com.dcsgo.library.client.service.IBorrowRecordsService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;


/**
 * @author Dcsgo
 * @since 2024-09-02
 */
@Slf4j
@Service
public class BorrowRecordsServiceImpl extends ServiceImpl<BorrowRecordsMapper, BorrowRecord> implements IBorrowRecordsService {
    @Override
    public List<BorrowRecordVO> queryBorrowRecordsByUserId(Long userId) {
        List<BorrowRecord> borrowRecords = Db.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId)
                .eq(BorrowRecord::getStatus, BookStatus.BORROWING)
                .list();
        if(borrowRecords.isEmpty()){
            return Collections.emptyList();
        }
        List<Long> borrowedCopiesIds = borrowRecords.stream().map(BorrowRecord::getBookCopiesId).toList();
        List<Long> bookIds = Db.lambdaQuery(BookCopies.class)
                .in(BookCopies::getId, borrowedCopiesIds)
                .list()
                .stream().map(BookCopies::getBookId).toList();
        List<Book> books = Db.lambdaQuery(Book.class)
                .select(Book::getTitle)
                .in(Book::getId, bookIds)
                .list();
        List<BorrowRecordVO> borrowRecordVOS = BorrowRecordVO.of(borrowRecords);
        for (int i = 0; i < books.size(); i++) {
            borrowRecordVOS.get(i).setTitle(books.get(i).getTitle());
        }
        return borrowRecordVOS;
    }
}
